package com.fengze.business.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.fengze.business.domain.AuditOpinion;
import com.fengze.business.domain.FileInfo;
import com.fengze.business.enums.AuditStatusEnum;
import com.fengze.business.enums.BusinessTypeEnums;
import com.fengze.business.enums.PaymentStatusEnum;
import com.fengze.business.mapper.*;
import com.fengze.business.query.PaymentFinishReqParam;
import com.fengze.business.query.PaymentReqParam;
import com.fengze.business.resp.PaymentRespDetail;
import com.fengze.common.annotation.AutoSetInsertValue;
import com.fengze.common.annotation.AutoSetUpdateValue;
import com.fengze.common.config.RuoYiConfig;
import com.fengze.common.core.domain.model.LoginUser;
import com.fengze.common.utils.SecurityUtils;
import com.fengze.common.utils.file.FileUploadUtils;
import org.springframework.stereotype.Service;
import com.fengze.business.domain.Payment;
import com.fengze.business.service.IPaymentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 付款Service业务层处理
 * 
 * @author lug
 * @date 2024-12-10
 */
@Service
public class PaymentServiceImpl implements IPaymentService 
{
    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private AuditOpinionMapper auditOpinionMapper;

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Resource
    private ContractInfoMapper contractInfoMapper;


    /**
     * 查询付款
     * 
     * @param id 付款主键
     * @return 付款
     */
    @Override
    public Payment selectPaymentById(Long id)
    {
        return paymentMapper.selectPaymentById(id);
    }

    /**
     * 查询付款列表
     * 
     * @param payment 付款
     * @return 付款
     */
    @Override
    public List<Payment> selectPaymentList(Payment payment)
    {
        return paymentMapper.selectPaymentList(payment);
    }

    /**
     * 新增付款
     * 
     * @param payment 付款
     * @return 结果
     */
    @AutoSetInsertValue
    @Override
    public int insertPayment(Payment payment)
    {
        payment.setAuditStatus(AuditStatusEnum.DRAFT.getStatus());
        payment.setPaymentStatus(PaymentStatusEnum.UN_PAY.getStatus());
        return paymentMapper.insertPayment(payment);
    }

    /**
     * 修改付款
     * 
     * @param payment 付款
     * @return 结果
     */
    @AutoSetUpdateValue
    @Override
    public int updatePayment(Payment payment)
    {
        return paymentMapper.updatePayment(payment);
    }

    /**
     * 批量删除付款
     * 
     * @param ids 需要删除的付款主键
     * @return 结果
     */
    @Override
    public int deletePaymentByIds(Long[] ids)
    {
        return paymentMapper.deletePaymentByIds(ids);
    }

    /**
     * 删除付款信息
     * 
     * @param id 付款主键
     * @return 结果
     */
    @Override
    public int deletePaymentById(Long id)
    {
        return paymentMapper.deletePaymentById(id);
    }

    @Override
    public List<Payment> listAll(PaymentReqParam param) {
        return paymentMapper.selectAll(param);
    }



    @AutoSetInsertValue
    @Override
    public int submit(Payment payment) {
        payment.setAuditStatus(AuditStatusEnum.PROCESSING.getStatus());
        payment.setPaymentStatus(PaymentStatusEnum.UN_PAY.getStatus());
        if (payment.getId() == null) {
            return paymentMapper.insertPayment(payment);
        }
        return paymentMapper.updatePayment(payment);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int finish(PaymentFinishReqParam param) {
        Payment payment = new Payment();
        payment.setPaymentStatus(PaymentStatusEnum.PAYED.getStatus());
        payment.setId(param.getId());
        payment.setPaymentDate(param.getPaymentDate());
        payment.setPaymentDes(param.getPaymentDes());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payment.setPaymentUserId(loginUser.getUserId());
        payment.setPaymentOpDate(new Date());
        payment.setPaymentUserName(loginUser.getUser().getNickName());
        // 上传附件
        MultipartFile[] files = param.getFiles();
        if(files != null && files.length > 0){
            for (MultipartFile file : files) {
                if(!file.isEmpty()){
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
                    // 上传并返回新文件名称
                    String fileName = null;
                    try {
                        fileName = FileUploadUtils.upload(filePath, file);
                        FileInfo fileInfo = new FileInfo();
                        fileInfo.setStatus(0);
                        fileInfo.setBusiId(param.getId());
                        fileInfo.setBusiType(BusinessTypeEnums.PAYMENT.getCode());
                        fileInfo.setFileName(file.getOriginalFilename());
                        fileInfo.setFileType(FileUploadUtils.getExtension(file));
                        fileInfo.setFileSize(file.getSize());
                        fileInfo.setFileUrl(fileName);
                        fileInfoMapper.insertFileInfo(fileInfo);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        Payment moneyPayment = paymentMapper.selectPaymentById(payment.getId());
        if(moneyPayment.getProjectId() != null || moneyPayment.getContractId() != null){
            // 更新项目和和同的付款金额
            if(moneyPayment.getProjectId() != null){
                projectInfoMapper.addPaymentMoney(moneyPayment.getProjectId() ,moneyPayment.getPaymentMoney());
            }
            if(moneyPayment.getContractId() != null){
                contractInfoMapper.addPaymentMoney(moneyPayment.getContractId(),moneyPayment.getPaymentMoney());
            }
        }
        return paymentMapper.updateFinish(payment);
    }

    @Override
    public PaymentRespDetail getDetail(Long id) {
        PaymentRespDetail detail = new PaymentRespDetail();
        List<FileInfo> fileInfos = fileInfoMapper.selectListByBusiIdAndType(id, BusinessTypeEnums.PAYMENT.getCode());
        List<AuditOpinion> auditList = auditOpinionMapper.selectByBusi(id,BusinessTypeEnums.PAYMENT.getCode());
        Payment payment = paymentMapper.selectPaymentById(id);
        detail.setPayment(payment);
        detail.setFiles(fileInfos);
        detail.setAuditList(auditList);
        return detail;
    }
}
